<?php

namespace App\Kuafu\Customer\Controller\Applet;

use App\Kuafu\Activity\Enum\ActivityEnum;
use App\Kuafu\Base\Controller\BaseController;
use App\Kuafu\Customer\Enum\CodeEnum;
use App\Kuafu\Customer\Enum\CustomerCodeEnum;
use App\Kuafu\Customer\Exceptions\CustomerException;
use App\Kuafu\Customer\Service\CustomerPlatformService;
use App\Kuafu\Customer\Service\CustomerSendCouponLogService;
use App\Kuafu\Customer\Service\CustomerService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class CustomerPlatformController extends BaseController
{
    /**
     * 检查用户有没有绑定手机号
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Kuafu\Customer\Exceptions\CustomerException
     */
    public function getUserInfo(Request $request)
    {
        //获取用户id
        $userId = CustomerPlatformService::getUserId($request);
        //查询用户缓存
        $userInfo = Redis::get(CodeEnum::PREFIX_PLATFORM . $request->header('platformId') . ':' . CodeEnum::PREFIX_USERID . $userId);
        $userInfo = json_decode($userInfo, true);
        if (!$userInfo) {
            $userInfo = [
                'name'           => '',
                'mobile'         => '',
                'headImage'      => '',
                'isRegisterSend' => false
            ];
            //查询用户信息
            if ($userId) {
                //查询用户信息
                $columnValue = ['id' => $userId];
                $field       = ['name', 'mobile', 'headImage'];
                $userInfo    = CustomerService::getUserInfo($columnValue, $field);
                $userInfo    = $userInfo->toArray();
                //查询用户注册有礼是否领券
                $isSend                     = CustomerSendCouponLogService::checkIsSend($userId,
                    ActivityEnum::TYPE_REGISTRATION);
                $userInfo['isRegisterSend'] = $isSend;
            }
            Redis::setex(CodeEnum::PREFIX_PLATFORM . $request->header('platformId') . ':' . CodeEnum::PREFIX_USERID . $userId,
                3600, json_encode($userInfo));
        }
        return $this->success($userInfo);
    }

    /**
     * 获得最新券包信息
     * 获得用户是否购买信息
     * @throws CustomerException
     */
    public function getCouponDetail(Request $request)
    {
        //获取用户id
        $userId          = CustomerPlatformService::getUserId($request);
        $shopId          = $request->header('shopId', 0);
        $couponPackageId = $request->get('couponPackageId', 0);
        if (!$shopId) {
            throw new CustomerException(CustomerCodeEnum::ERR_CUSTOMER_PARAM_VALID);
        }
        return $this->success(CustomerPlatformService::couponPackageInfo($shopId, $userId, $couponPackageId));
    }
}
